<?php
/**
 * 快速单表数据获取
 *
 * @param $table	表名
 * @param null $id	主键值
 * @param null $field	字段名
 * @return mixed
 */
function table($table, $id = null, $field = null)
{
	$truetable = C('DB_PREFIX') . $table;
	$Db = Db::getInstance();

	// 获取表主键
	$fields = $Db->getFields($truetable);
	foreach ($fields as $key => $val) {
		if ($val['primary']) {
			$primary = $key;
			break;
		}
	}

	// 整个表数据
	if (is_null($id)) {
		static $result;
		if (!isset($result[$table])) {
			$array = array();
			$fields = is_null($field) ? '*' : (strpos($field, $primary) === false ? $primary . ',' . $field : $field);
			$data = $Db->query("SELECT $fields FROM `$truetable` ORDER BY `$primary`");
			$result[$table] = field_index($data, $primary);
		}
		return $result[$table];

	// 单条记录
	} else {
		static $row;
		$key = $truetable . '_' . $id;
		if (!isset($row[$key])) {
			$data = $Db->query("SELECT * FROM `$truetable` WHERE `$primary`=$id");
			$row[$key] = $data[0];
		}
		return (is_null($field) && !isset($row[$key][$field])) ? $row[$key] : $row[$key][$field];
	}
}

/**
 * 二维数组索引格式化
 *
 * @param $array
 * @param $field
 * @return array|bool
 */
function field_index($array, $key)
{
	if (is_array($array)) {
		foreach ($array as $k => $v) {
			if (!isset($v[$key])) break;
			$index = $v[$key];
			$result[$index] = $v;
		}
		return $result;
	}
	return false;
}

/**
 * FirePHP 调试接口
 *
 * @param $message
 * @param bool $showtime
 */
function console($message, $showtime = false)
{
	static $lasttime, $fb = null;
	global $_beginTime;

	$lasttime = $_beginTime;

	if ($fb == null) {
		import('@.Helper.Firebug');
		$fb = FirePHP::getInstance(true);
	}

	$thistime = microtime(true);
	$usedtime = $thistime - $lasttime;
	$label = $showtime ? sprintf("%09.5fs", $usedtime) : null;
	$fb->info($message, $label);
	$lasttime = $thistime;
}

/**
 * 递归计算数组维度
 * @param $array
 * @param int $deep
 * @return mixed
 */
function array_dimension($array, $deep = 0)
{
    static $dimension = 0;
    if (is_array($array)) {
        $deep++;
        $dimension = ($deep > $dimension) ? $dimension+1 : $dimension;
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                array_dimension($value, $deep);
            }
        }
    }
    return $dimension;
}